import { Button, Card, Form, Input } from "antd";
import { login, getUserInfo } from "@/api/user"
import { useNavigate } from 'react-router-dom';
import { useDispatch } from "react-redux"
import { userInfo } from '@/store/user/types'
import { PropsTypes } from "./type"
import React from "react";
import { encrypt } from "@/utils/rsa";
type FieldType = {
    username: string;
    password: string;
};
const Lgoin: React.FC<PropsTypes> = ({ changeType }) => {
    const navigate = useNavigate();
    const dispatch = useDispatch()
    const validatePass = (_rule: any, value: any) => {
        if (!value) {
            return Promise.reject('请输入密码')
        } else {
            return Promise.resolve()
        }
    };
    const onFinish = async (e: FieldType) => {
        e.password = encrypt(e.password) || ''
        const u: string = await login(e)
        localStorage.setItem("token", u)
        dispatch({ type: 'setToken', value: u })
        const info: userInfo = await getUserInfo()
        dispatch({ type: 'setUserInfo', value: info })
        dispatch({ type: "setShopsOptions", value: info.shops })
        navigate("/")

    }
    const onFinishFailed = () => {
    }
    const handleChange = () => {
        changeType(true)
    }
    return (
        <Card title="登陆" bordered={false} styles={{ header: { textAlign: "center" } }}>
            <Form
                name="basic"
                labelCol={{ span: 5 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
            >
                <Form.Item<FieldType>
                    label="用户名"
                    name="username"
                    rules={[{ required: true, message: '请输入用户名!' }]}
                >
                    <Input />
                </Form.Item>

                <Form.Item<FieldType>
                    label="密码"
                    name="password"
                    rules={[{ required: true, validator: validatePass }]}
                >
                    <Input.Password />
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 2, span: 22 }} className="flex-end">
                    <Button type="link" onClick={handleChange}>
                        注册
                    </Button>
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 2, span: 22 }}>
                    <Button type="primary" htmlType="submit" style={{ width: "100%" }}>
                        登陆
                    </Button>
                </Form.Item>
            </Form>
        </Card>
    )
}
export default Lgoin